import re

from django.contrib.auth.backends import ModelBackend
from requests import Response

from personal.models import User


class UsernameMobileModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        filter = {}
        if re.match(r'^1[3-9]\d{9}$', username):
            filter.update({'mobile': username})
        else:
            filter.update({'username': username})
        try:
            user = User.objects.get(**filter)
        except User.DoesNotExist:
            return Response({'message': '用户名或密码错误'})
        if not user.check_password(password):
            return Response({'message': '用户名或密码错误'})

        return user
